<template>
  <el-dialog v-model="visible" title="添加公司">
    <el-form ref="formRef" :model="company">
      <el-form-item label="公司名称" prop="company_name">
        <el-input v-model="company.company_name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button class="ml-auto" @click="submitForm" v-loading="isLoading" type="primary">添加</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import {ElMessage, type FormInstance} from "element-plus";
import {useMutation} from "@pinia/colada";
import type {CompanyVO} from "../../../types";
import {insertCompany} from "../../../api/company.ts";
import {ref, useTemplateRef} from "vue";

const company = ref<CompanyVO>({});

const visible = defineModel({default: false});

const formEl = useTemplateRef<FormInstance>("formRef")
const emits = defineEmits<{
  success: []
}>();

const submitForm = async () => {
  await formEl.value?.validate((valid) => {
    if (valid) {
      insertCompanyFn(company.value)
    }
  })
}

let {mutate: insertCompanyFn, isLoading} = useMutation({
  mutation: (company: CompanyVO) => insertCompany(company),
  onSuccess: () => {
    visible.value = false
    formEl.value?.resetFields()
    emits("success")
    ElMessage.success("添加成功")
  },
  onError: () => {
    ElMessage.error("添加失败")
  }
});
</script>

<style scoped>

</style>